﻿using BasicInformation.ApiRead.Application.Command.Inventorys;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using SqlSugar;
using System.Net.NetworkInformation;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Inventorys
{
    public class GetDetailsHandler : IRequestHandler<GetDetailsCommand, ApiPaging<DetailsDTO>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetDetailsHandler> logger;

        public GetDetailsHandler(DatabaseContext db,ILogger<GetDetailsHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiPaging<DetailsDTO>> Handle(GetDetailsCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<DetailsDTO> paging = new ApiPaging<DetailsDTO>();
            StringBuilder sql= new StringBuilder();
            StringBuilder countSql= new StringBuilder();
            sql.Append(@"SELECT
                          b.ProductId,
                          b.ProductCode,
                          b.ProductName,
                          b.Specifications,
                          b.UnitId,
                          d.UnitName,
                          a.BookInventory,
                          a.BookAmount,
                          a.LocationId,
                          c.LocationName,
                          a.InventoryNumber,
                          a.ProfitLossNumber,
                          a.InventoryState,
                          a.ProfitLossAmount,
                          a.Price,
                          a.ProfitLossState 
                        FROM
                          inventorysmodel a
                          RIGHT JOIN productmodel b ON a.ProductId = b.ProductId
                          LEFT JOIN locationmodel c ON a.LocationId = c.LocationId
                          LEFT JOIN unitmodel d ON b.UnitId = d.UnitId 
                          WHERE b.IsDel=0");
            countSql.Append(@"  SELECT COUNT(*) FROM inventorysmodel");

            sql.Append(@"  ORDER BY b.CreatTime LIMIT @size OFFSET @offset");
            var parameters = new
            {
                size=request.size,
                offset=(request.index-1)*request.size,
            };
            var pageData=await db.DapperConnection.QueryAsync<DetailsDTO>(sql.ToString(),parameters);
            var totalCount=await db.DapperConnection.ExecuteScalarAsync<int>(sql.ToString(),parameters);
            int totalPage=(int)Math.Ceiling(totalCount/(double)request.size);

            paging.Msg = "库存盘点查询成功";
            paging.Code = ApiEnum.OK;
            paging.Data = pageData.ToList();
            return await Task.FromResult(paging);
        }
    }
}
